import time
import requests
import subprocess
import traceback

BASE_URL = "https://automatic-android-api.jobeyond.cn"
TOKEN = "2W93grF60JDqnFEI"

def http_post(api: str, params: dict) -> dict:
    """
    发送POST请求，参数为JSON，返回JSON对象。

    :param url: 请求的URL
    :param data: 请求体，字典类型
    :param headers: 可选，请求头
    :return: 响应的JSON对象
    """
    headers = {
        "Content-Type": "application/json",
        "x-token": TOKEN,
    }
    response = requests.post(f"{BASE_URL}{api}", json=params, headers=headers)
    response.raise_for_status()
    res_json = response.json()
    code = res_json.get("code")
    message = res_json.get("message")
    body = res_json.get("body")
    return {"code": code, "message": message, "body": body}
def adb_disconnect():
    """
    断开所有 ADB 连接
    :return: code ("SUCCESS" or "ERROR"), message (返回信息)
    """
    command = "adb disconnect"
    print(f"执行命令: {command}")
    try:
        result = subprocess.run(command, shell=True, encoding="utf-8", capture_output=True, text=True)
        
        if "disconnected" in result.stdout:
            return "SUCCESS", result.stdout.strip()
        else:
            return "ERROR", result.stderr.strip() if result.stderr else result.stdout.strip()
    
    except Exception as e:
        traceback.print_exc()
        return "ERROR", f"发生错误: {e}"
    
def adb_connect_devices(device_address):
    """
    连接到指定设备
    :param device_address: 设备 IP 和端口，例如 "172.30.6.152:40917"
    :return: code ("SUCCESS" or "ERROR"), message (返回信息)
    """
    command = f"adb connect {device_address}"
    print(f"执行命令: {command}")
    try:
        result = subprocess.run(command, shell=True,encoding="utf-8", capture_output=True, text=True)
        
        if "connected to" in result.stdout:
            return "SUCCESS", result.stdout.strip()
        else:
            return "ERROR", result.stderr.strip() if result.stderr else result.stdout.strip()
    
    except Exception as e:
        traceback.print_exc()
        return "ERROR", f"发生错误: {e}"
def adb_list_devices():
    # 执行 adb devices 并获取输出
    output = subprocess.check_output(
        ["adb", "devices"],
        stderr=subprocess.STDOUT
    ).decode('utf-8')

    # 解析输出，忽略标题行和空行
    lines = [l.strip() for l in output.splitlines()]
    device_lines = [
        l for l in lines if l and not l.startswith("List of devices")
    ]

    # 提取设备 ID（IP:端口 或 序列号）
    return [l.split()[0] for l in device_lines]

def task(taskId,deviceId) -> dict:
    print(f"开始创建任务: taskId={taskId}, deviceId={deviceId}")
    (code, message, body) = http_post("/a/task/create", {
        "taskId": taskId,
        "deviceId": deviceId,
    }).values()
    if code != "SUCCESS":
        return {"code": "ERROR", "message": f"创建任务失败: {taskId} {code} {message}"}
    
    task_log_id = body.get("id")
    (code, message, body) = http_post("/a/task/push", {
        "id": task_log_id,
    }).values()
    if code != "SUCCESS":
        return {"code": "ERROR", "message": f"推送任务失败: {taskId} {task_log_id} {code} {message}"}
    
    while True:
        (code, message, task_info) = http_post("/a/task/info", {
            "id": task_log_id,
        }).values()
        print(f"任务状态: taskId={taskId}, task_log_id={task_log_id}, code={code}, status={task_info.get('status')}, message={message}")
        if code != "SUCCESS":
            return {"code": "ERROR", "message": f"获取任务状态失败: {taskId} {task_log_id} {code} {message}"}
        
        status = task_info.get("status")
        if status == "over":
            message = task_info.get("message")
            if message:
                return {"code": "ERROR", "message": f"任务执行失败: {taskId} {task_log_id} {message}"}
            return {"code": "SUCCESS", "message": f"任务执行成功: {taskId} {task_log_id}"}
        
        # 等待一段时间后重试
        time.sleep(5)

def get_device_address(device_id: str) -> dict:
    """
    根据安卓id生成链接字符串。

    :param device_id: 安卓设备ID
    :return: 链接字符串
    """
    (code, message, device_info) = http_post("/a/device/info", {"id": device_id}).values()
    if code != "SUCCESS":
        return {"code": "ERROR", "message": f"获取设备信息失败: {device_id} {code} {message}"}
    
    vpn_ip = device_info.get("vpnIp")
    debug_port = device_info.get("debugPort")
    device_address = f"{vpn_ip}:{debug_port}"
    print(f"device_address: {device_address}")
    adb_devices = adb_list_devices()
    print(f"adb_devices: {adb_devices}")
    if device_address not in adb_devices:
        (code, message) = task("check_vpn_status", device_id).values()
        if code != "SUCCESS":
            return {"code": "ERROR", "message": f"{message}"}
        
        (code, message) = task("check_debugger_port", device_id).values()
        if code != "SUCCESS":
            return {"code": "ERROR", "message": f"{message}"}
        
        (code, message, device_info) = http_post("/a/device/info", {"id": device_id}).values()
        if code != "SUCCESS":
            return {"code": "ERROR", "message": f"获取设备新信息失败: {device_id} {code} {message}"}
        
        vpn_ip = device_info.get("vpnIp")
        debug_port = device_info.get("debugPort")
        device_address = f"{vpn_ip}:{debug_port}"

        code, message = adb_connect_devices(device_address)
        if code != "SUCCESS":
            return {"code": "ERROR", "message": f"设备连接失败。{message}"}
    
    return {"code": "SUCCESS", "message": "", "device_address": device_address}